package com.anpxd.erpad.adapter

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.anpxd.erpad.App
import com.anpxd.erpad.BR
import com.anpxd.erpad.R
import com.anpxd.erpad.net.UrlConfig
import com.anpxd.erpad.bean.Car
import com.gg.image.config.GlideApp
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.uuzuche.lib_zxing.activity.CodeUtils

/**
 * Creator : GG
 * Date    : 2018/1/19
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
class CarItemAdapter : BaseQuickAdapter<Car, CarItemAdapter.CarViewHolder>(R.layout.item_car_detail, listOf<Car>()) {


    override fun convert(helper: CarViewHolder, item: Car) {
        helper.bind.apply {
            setVariable(BR.car, item)
            executePendingBindings()
        }
        helper.setText(R.id.prompt2, "联系电话：" + item.user?.userMobile)
        val imageView = helper.getView<ImageView>(R.id.car_photo)
        val qrView = helper.getView<ImageView>(R.id.qr_code)
        GlideApp.with(mContext).load(App.instance.getImageUrl() + item.carImageUrl + ".r_1100xh_800").error(R.drawable.ic_place).centerCrop().placeholder(R.drawable.ic_place).into(imageView)

        var bitmap: Bitmap? = null
        if (item.isShow) {
            bitmap = CodeUtils.createImage(UrlConfig.getShareUrl(item.carId!!), 400, 400, BitmapFactory.decodeResource(mContext.resources, R.mipmap.ic_launcher))
            GlideApp.with(mContext).load(bitmap).into(qrView)
        } else {
            bitmap?.recycle()
        }
        if (item.carRetailPrice ?: 0.0 > 0) {
            helper.setText(R.id.car_price, item.carRetailPrice.toString())
                    .setGone(R.id.car_price_ll, true)
                    .setGone(R.id.negotiable, false)
        } else {
            helper.setGone(R.id.car_price_ll, false)
                    .setGone(R.id.negotiable, true)
        }
    }

    override fun getItemView(layoutResId: Int, parent: ViewGroup?): View {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(mLayoutInflater, layoutResId, parent, false)
                ?: return super.getItemView(layoutResId, parent)
        return binding.root.apply {
            setTag(R.id.dataBinding, binding)
        }
    }

    inner class CarViewHolder(view: View) : BaseViewHolder(view) {
        val bind: ViewDataBinding
            get() = itemView.getTag(R.id.dataBinding) as ViewDataBinding
    }
}